// pages/carte/index.js
var app = getApp();
var weChatInfo = wx.getStorageSync('weChatInfo');
var util = require('../../utils/util.js');
var address = app.globalData.address;
var that; 
//播放录音对象
var innerAudioContext = null;
Page({
  indexCarteIntroduction: 1,
  data: {
    idx:1,
    mapStatus:0,
    swiperIndex: 1,
    load:true,
    show: true,
    showModalStatus:false,//是否弹起底部框
    noneLive:true,//是否点击语音播放
    open:true,//是否点击展开名片信息
    list: [],
    // danmuList: [
    //   {
    //     text: '666',
    //     color: '#ff0000',
    //     time: 1
    //   },
    //   {
    //     text: '值得推荐',
    //     color: '#00ff00',
    //     time: 2
    //   },
    //   {
    //     text: '好厉害的说',
    //     color: '#ff0000',
    //     time: 3
    //   },
    //   {
    //     text: '啦啦啦啦',
    //     color: '#00ff00',
    //     time: 4
    //   },
    //   {
    //     text: '兄弟可以直接联系你吗',
    //     color: '#ff0000',
    //     time: 5
    //   },
    //   {
    //     text: '666',
    //     color: '#00ff00',
    //     time: 6
    //   },
    //   {
    //     text: '赞',
    //     color: '#ff0000',
    //     time: 7
    //   },
    //   {
    //     text: '666',
    //     color: '#00ff00',
    //     time: 8
    //   }
    // ],
  },
  /*点击地址显示隐藏地图 */
  indexapMap: function () {
    if (this.data.mapStatus == 0) {
      let list = that.data.list.myMessage;
      let latitude = parseFloat(list.latitude);
      let longitude = parseFloat(list.longitude);
      wx.openLocation({
        latitude: latitude,
        longitude: longitude,
        name: that.data.list.companyAddress,
        scale: 28
      })
      // this.setData({
      //   condition: true,
      //   mapStatus: '1'
      // })
    } else {
      this.setData({
        condition: false,
        mapStatus: '0'
      })
    }

  },
  swpBtn: function (e) {
    var swiperList = this.data.swiperList;
    var max = swiperList.length;
    var idx = e.currentTarget.dataset.index;

    var prev = swiperList[idx - 1];//前一个
    var next = swiperList[idx + 1];//后一个
    var curView = swiperList[idx];//当前
    if (curView.swpClass === 'swp-center') {//如果当前是在中间的，即可跳转
      /*wx.navigateTo({
        url: curView.aurl,
      })*/
    }

    if (prev) {//如果当前的前面有
      if (next) {//当前的后面有
        next.swpClass = "swp-right";
      }
      prev.swpClass = "swp-left";
      curView.swpClass = "swp-center";
      for (var i = 0; i < idx; i++) { //当前前一个的前面所有
        swiperList[i].swpClass = 'swp-leftNo'
      }
    }
    if (next) {//如果当前的后面有
      if (prev) {//当前的前面有
        prev.swpClass = "swp-left";
      }
      curView.swpClass = "swp-center";
      next.swpClass = "swp-right";
      for (var i = (idx + 2); i < max; i++) {//当前后一个的后面所有
        swiperList[i].swpClass = 'swp-rightNo'
      }
    } else {
      prev.swpClass = "swp-left";
      curView.swpClass = "swp-center";
    }
    this.setData({
      swiperList: swiperList,
      idx:idx
    })
  },
// 是否点击展开更多名片信息
  toOpen:function(e){
    that.setData({
      open:!that.data.open
    })
  },
  // 点击我推荐商品中的更多跳转到商城
  toSwitchTab:function(){
      wx.switchTab({
        url: '../mall/mall',
      })
  },
  // 点击我推荐的商品图片进去具体某一个商品详情
  toDetail:function(e){
     var id = e.currentTarget.dataset.mallid;    //此处应该动态的获取该商品id，并传值至下一个页面
    wx.navigateTo({
      url: '../mall/subPackages/mall-details/mall-details?informationid='+id,
    })
  },
  // 点击查看更多跳转至查看人数页面
  toMore:function(e){
    let id = that.data.list.id;
    
    wx.navigateTo({
      url: 'subPackages/check-more/check-more',
    })
  },
  // 点击生成海报按钮
  toPoster:function(){
    wx.navigateTo({
      url: 'subPackages/poster/poster',
    })
  },
  onShow: function () {
    that = this;
    if (app.globalData.indexNeedReload){
      app.globalData.indexNeedReload=false;
      if (wx.getStorageSync('id')) {
        let id = wx.getStorageSync('id');
        that.setData({
          id: id
        })
      }
      app.getUserInfo(function (r) {
        that.showList();
      })
    }
  },
  // 点击了视频
  toVideo:function(e){
    console.log(e)
    let src = e.currentTarget.dataset.src;
    wx.navigateTo({
      url: 'subPackages/video/video?src=' + src,
    })
  },
  // 网页加载即调用
  onLoad:function(options){
    // console.log('index onload')
    that = this;
    if (options.gainChannel){
      let gainChannel = options.gainChannel;
      let transmitPeople = options.transmitPeople;
      wx.setStorageSync('gainChannel', gainChannel);
      wx.setStorageSync('transmitPeople', transmitPeople);
    }
    if (wx.getStorageSync('id')){
      let id = wx.getStorageSync('id');
      that.setData({
        id:id
      })
    }
    if(options.id){
      let id = options.id;
      wx.setStorageSync('id', id);
      that.setData({
        id: id
      })
    }
    app.getUserInfo(function (r) {
      that.showList();
    })
    
    wx.getSystemInfo({
      success: function (res) {
        if (res.platform == 'ios') {//为了ios兼容
          innerAudioContext = wx.getBackgroundAudioManager();
        } else {
          innerAudioContext = wx.createInnerAudioContext();
        }
      },
    })    

    innerAudioContext.onPlay(() => {
      console.log('开始播放')
    })
    innerAudioContext.onEnded((res) => {
      that.setData({
        noneLive: true
      })
    })
  },
  // 更新人气
  updateMoods: function (id) {
    wx.request({
      url: address + 'Business/updateMoods',
      data: {
        businessId: id
      },
      success: function (result) {
        let data = result.data;
        if(data == 1){
          console.log('人气+1成功')
        }
      }
    })
  },
  // 存入手机通讯录
  addPhoneContact:function(e){
    wx.addPhoneContact({
      firstName: that.data.list.name,//联系人姓名
      mobilePhoneNumber: that.data.list.myMessage.phone,//联系人手机号
    })
    let url = address + 'Interaction/savePhone';
    let params = {
      businessId: that.data.bId,
      evenType:3,
      message:'手机到通讯录'
    };
    let sessionId = app.globalData.sessionId;
    util.nomeRequest(url, params,sessionId,function(res){
      if(res == 1){
        console.log('记录保存手机成功')
      }
      
    },function(){

    });

  },
  // 复制内容到剪切板
  copy: function (e) {
    that = this;
    var title = e.currentTarget.dataset.title;
    var flex = e.currentTarget.dataset.flex;
    wx.setClipboardData({
      data: title,//此复制版数据为模拟数据，真实数据应该从data中取出来，有待完善
      success: function (res) {
      }
    });
    let url;
    let params = {
      businessId: that.data.bId,
      evenType: 2
      };
    let sessionId = app.globalData.sessionId;
    if(flex == 1){//复制微信
      url = address + 'Interaction/copyWechat';
      params.message =  '微信';
    }
    if (flex == 2) {//复制邮箱
      url = address + 'Interaction/copyEmail';
      params.message = '邮箱';
    }
    if (flex == 3) {//复制公司名称
      url = address + 'Interaction/copyCompany';
      params.message = '公司名称';
    }
    if (flex == 4) {//复制公司地址
      url = address + 'Interaction/navigationLocation';
      params.message = '公司地址';
    }
    util.nomeRequest(url, params,sessionId,function(res){
      if (res == 1){
        console.log('记录用户操作成功')
      }
      
    },function(){});
  },
  // 一键拨打电话
  calling: function () {
    if(this.data.p){
      this.onShareAppMessage();
    }else{
    wx.makePhoneCall({
      phoneNumber: that.data.list.myMessage.phone, //此号码并非真实电话号码，仅用于测试,要setData去动态控制号码
      success: function () {
        console.log("拨打电话成功！")
        let url = address + 'Interaction/dialMobile';
        let params = {
          businessId: that.data.bId,
          evenType: 4,
          message:'你的手机'
          };
        let sessionId = app.globalData.sessionId;
        util.nomeRequest(url,params,sessionId,function(res){
          if(res == 1){
            console.log('记录用户拨打手机成功')
          }          
        },function(){});
      },
      fail: function () {
        console.log("拨打电话失败！")
      }
    })
    }
  },

// 网页加载即请求后台数据

 showList:function(e){
   if (that.data.id==undefined){
     wx.navigateTo({
       url: 'subPackages/cardList/cardList?sessionId=' + sessionId,
     }) 
     return;
   }
  

   let url = address + 'Business/showBusiness';
   let params = {
     id: that.data.id
   };
   if (wx.getStorageSync('transmitPeople') && wx.getStorageSync('gainChannel')){
     params.transmitPeople = wx.getStorageSync('transmitPeople');
     params.gainChannel = wx.getStorageSync('gainChannel');
   }
   let sessionId = app.globalData.sessionId;
   util.headLoading(url, params, "正在加载中", sessionId,function(res){
     console.log(res)
    //  console.log(res.name.length)
     wx.setStorageSync('empty', res);
     let marker = [];
     let markers = {};
     markers.id = 0;
     markers.latitude = res.myMessage.latitude;
     markers.longitude = res.myMessage.longitude;
     markers.iconPath = '/icon/carte/map.png';
     markers.width = 35;
     markers.height = 35;
     marker.push(markers)
     let swiperList = res.swiperList;
     if (swiperList.length == 1) {
       swiperList.forEach(function (v, i) {
         if (i == 0) {
           v.swpClass = 'swp-center';
         } else if (i == 1) {
           v.swpClass = 'swp-right';
         }
         else {
           v.swpClass = 'swp-rightNo';
         }
       })
     } else {
       swiperList.forEach(function (v, i) {
         if (i == 0) {
           v.swpClass = 'swp-left';
         } else if (i == 1) {
           v.swpClass = 'swp-center';
         } else if (i == 2) {
           v.swpClass = 'swp-right';
         }
         else {
           v.swpClass = 'swp-rightNo';
         }
       })
     }
     that.updateMoods(res.id);//更新人气
     that.addBrowse(res.id);//增加一位浏览人
     wx.setStorageSync('bId', res.id)
     wx.setStorageSync('user', res);
     wx.setStorageSync('empId', res.empId);
     that.setData({
       list: res,
       swiperList: swiperList,
       markers: marker,
       bId: res.id
     })
     if (weChatInfo) {
       that.setData({
         show: false
       })
     } else {
       that.setData({
         show: true
       })
       setTimeout(function () {
         that.setData({
           show: true
         })
       }, 2000)
     }
   },function(){});
   
 },

  swiperChange(e) {
    this.setData({
      swiperIndex: e.detail.current
    })
  },

//  增加一位浏览人
  addBrowse:function(id){
    wx.request({
      url: address + 'Examine/addBrowse',
      data:{
        businessId:id
      },
      header: {
        'content-type': 'application/json', 'Cookie': 'JSESSIONID=' + app.globalData.sessionId
      },
      success:function(result){
        if(result.data == 1){
          console.log('增加浏览人成功')
        }else{
          console.log('增加浏览人失败')
        }
      }
    })
  },
  //显示对话框
  showModal: function (e) {
    this.setData({
      condition:false,
    })
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step();
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //点击靠谱添加次数
  toUpdateReliable:function(){
    let list = that.data.list;
    wx.request({
      url: address + 'Business/updateReliable',
      data:{
        businessId:list.id
      },
      header: {
        'content-type': 'application/json', 'Cookie': 'JSESSIONID=' + app.globalData.sessionId
      },
      success:function(result){
        if (result.data == 1){
          if (list.is_reliable == 0){
            list.is_reliable = 1;
            ++list.reliable;
            wx.showToast({
              title: '感谢你的认可！',
              icon: 'none',
              duration: 1200
            })
          }else{
            list.is_reliable = 0;
            --list.reliable;
          }
          
          
          that.setData({
            list:list
          })
        }
      }
    })
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },

  
  // 点击语音开始播放
  toLive: function (e) {
    let list = that.data.list;
    if (!list.listener){
      list.listener = true;
    }
    
    that.setData({
      noneLive: false,
      list:list
    })
    var u = e.currentTarget.dataset.url;
    console.log(u)
    if (u == that.data.srcurl) {
      that.setData({
        noneLive: true,
        srcurl: 'undefined',
      })
      // innerAudioContext.onStop();
      innerAudioContext.stop();//停止播放
      return;
    }
    that.setData({
      srcurl: u
    })
    innerAudioContext.stop();//停止播放

    innerAudioContext.autoplay = true;
    innerAudioContext.src = u;
    innerAudioContext.title = '录音';
    
  },
  //转发+1
  updateTransmit: function (id, sessionId){
    wx.request({
      url: address + 'Business/updateTransmit',
      data:{
        businessId:id
      },
      header: {
        //'Content-Type': 'application/json'
        'content-type': 'application/x-www-form-urlencoded', 'Cookie': 'JSESSIONID=' + sessionId
      },
      success:function(result){
        if(result.data == 1){
          console.log('转发成功+1')
        }
      }
    })
  },
  // 点击查看我的照片
  // toPrewImg:function(e){
  //   var url = e.currentTarget.dataset.url;
  //   wx.previewImage({
  //     current: url, // 当前显示图片的http链接
  //     urls: [url] // 需要预览的图片http链接列表
  //   })
  // },
  // 点击事件触发page执行转发的函数
  onShareApp: function () {
    this.onShareAppMessage();
  },
  // 在page定义转发函数
  onShareAppMessage: function (options) {
    let sessionId = app.globalData.sessionId;
    if (options.from == 'menu'){
      that.updateTransmit(that.data.list.id, sessionId);//转发+1
    } else if (options.from == 'button'){
      that.updateTransmit(that.data.list.id, sessionId);//转发+1
    }
    let id;
    if(that.data.id){
      id = that.data.id;
    } else if (that.data.list.id){
      id = that.data.list.id;
    }else{
      id = '';
    }
    let nickName = app.globalData.weChatInfo.nickName;
    let headPortraitAddress;
 
    headPortraitAddress = that.data.list.headPortraitAddress;
      return {
        title: '您好、' + that.data.list.coName+that.data.list.position+that.data.list.name+'。感恩缘分请惠存',
        imageUrl: headPortraitAddress,
        path: '/pages/index/index?id=' + id + '&transmitPeople=' + nickName + '&gainChannel=' + 1//此处要传入一个名片id去区分是哪个，即重新设定idx的值
      }
    
    
  },
// 点击左上角名片按钮跳转
  toCardList:function(e){
    let id = that.data.list.id;
    let companyId = that.data.list.companyId;
    wx.setStorageSync('check', false);
    wx.setStorageSync('count', 0);
    wx.setStorageSync('count1', 0);
    wx.setStorageSync('count2', 0);
    wx.navigateTo({
      url: 'subPackages/cardList/cardList?id=' + id + '&companyid=' + companyId,//此处应该带id跳转，名片列表如果是转发的话，只能查看当前这个信息
    })
  },

  testSubmit:function(e){
    util.testSubmit(e);
  },
  toChat:function(){
    wx.navigateTo({
      url: '../mall/subPackages/chat/chat',
    })
  },
  /**
* 生命周期函数--监听页面初次渲染完成
*/
  onReady: function () {
    //获得dialog组件
    this.dialog = this.selectComponent("#dialog");
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    innerAudioContext.stop();//停止播放
    that.setData({
      noneLive: true,
      srcurl: 'undefined',
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    // 显示顶部刷新图标
    wx.showNavigationBarLoading();
    var that = this;
    let url = address + 'Business/showBusiness';
    let params = {
      id: that.data.id
    };
    let sessionId = app.globalData.sessionId;
    util.nomeRequest(url, params,sessionId, function (res) {
      console.log(res)
      let marker = [];
      let markers = {};
      markers.id = 0;
      markers.latitude = res.myMessage.latitude;
      markers.longitude = res.myMessage.longitude;
      markers.width = 50;
      markers.height = 50;
      marker.push(markers)
      let swiperList = res.swiperList;
      if (swiperList.length == 1) {
        swiperList.forEach(function (v, i) {
          if (i == 0) {
            v.swpClass = 'swp-center';
          } else if (i == 1) {
            v.swpClass = 'swp-right';
          }
          else {
            v.swpClass = 'swp-rightNo';
          }
        })
      } else {
        swiperList.forEach(function (v, i) {
          if (i == 0) {
            v.swpClass = 'swp-left';
          } else if (i == 1) {
            v.swpClass = 'swp-center';
          } else if (i == 2) {
            v.swpClass = 'swp-right';
          }
          else {
            v.swpClass = 'swp-rightNo';
          }
        })
      }
      that.setData({
        list: res,
        swiperList: swiperList,
        markers: marker
      })
    }, function () { });
    setTimeout(function(){
      // 隐藏导航栏加载框
      wx.hideNavigationBarLoading();

      // 停止下拉动作
      wx.stopPullDownRefresh();
    },1000)
      
  },

  handleContact(e) {
    console.log(e)
    console.log(e.path)
    console.log(e.query)
  }

})
